const express = require('express')
const router = express.Router()

const {getDb, saveDb} = require('../utils/db')
const { decrypt, encrypt } = require('../utils/encryption')

router.post('/login',async (req,res)=>{
  const {name,passwordHash} = (req.body)
  try {
    const dbs = await getDb("../mock/users.json")
    const dbsKeys = Object.keys(dbs)
    const db = dbsKeys.find( dbsKey => passwordHash === dbsKey )
    if(db === undefined) {
      res.status(403).send('账户或密码不对')
    }
    const auths = Object.values(dbs)
    const auth = auths.find( auth => auth.name === name && decrypt(auth.passwordHash) === passwordHash)
    if(auth === undefined){
      res.status(200).send('账户或密码不对')
    }
    res.status(200).json(auth)
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
})

router.post('/register',async (req,res)=>{
  try {
    let auths = await getDb("../mock/users.json");
    let {name,passwordHash:password}  = (req.body)
    password = encrypt(password)
    const b = new Object()
    b[password] = {
      id:password,
      name,
      passwordHash:password
    }
    Object.assign(auths,b)
    await saveDb(auths,"../mock/users.json")
    res.status(200).send("注册成功")

  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
})

module.exports = router